package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.getProperty
import groovy.json.JsonSlurper
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: HST_API_SftpFile_Client_Tag
 * @Description: 华盛 企业微信读取（SFTP） 客户标签同步（增量）--内部接口
 * @author: join* @date 2021-07-26 11:00:00
 *
 */

public class HST_API_SftpFile_Client_Tag implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(HST_API_SftpFile_Client_Tag.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("utf-8");

        log.debug("-------------------------start HST_API_SftpFile_Client_Tag 开始调用-----------------");
        log.debug("request请求----------------:" + request);


        String getMethod = request.getMethod();
        String callJson = "";
        BufferedReader iny = null;

        def reJson = "";
        def dataSourceID = "dataSource";

        log.debug("getMethod:" + getMethod);
        if (getMethod.equals("GET")) {
            callJson = request.getParameter("jsondata");
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callJson += line;
            }
        }

        log.debug("callJson:" + callJson);
        try {

            // 调用处理信息手动参数
            JSONObject inObject = new JSONObject(callJson);
            log.debug("处理前的Json：" + inObject.toString());
            String hsttype = GetJV(inObject, "hsttype");//获取是否是手动调用 1001
            String datetime = GetJV(inObject, "datetime");//时间 20210723

            //获取配置参数
            String doURL = getProperty.get("HSTIP");//华盛通SFTPIP
            String HSTDEVHST = getProperty.get("HSTDEVHST");//华盛通SFTP用户名
            String HSTPWD = getProperty.get("HSTPWD");//华盛通SFTP密码
            String HSTPORT = getProperty.get("HSTPORT");//华盛通SFTP端口
            String HSTPATH = getProperty.get("HSTPATH");//华盛通SFTP文件路径
            //String HSTFINAME = getProperty.get("HSTFINAME");//华盛通SFTP文件名称 chat_msg_
            String LOACLPATH = getProperty.get("LOACLPATH");//存储下来的路径

            def getSelectSQL =	eliteBean.chaxun_sql("select  DATE_FORMAT(date_sub(curdate(),interval 1 day),'%Y%m%d') as nowtime,UUID() as  guid ","dataSource")
            String time2= getSelectSQL.get(0).get("nowtime");
            String guid= getSelectSQL.get(0).get("guid");
            log.debug("时间段=======：" + time2+"	guid:"+guid);
            /*
             String guid = UUID.randomUUID().toString();
             log.debug("时间段=======：" + time2+"	批次guid:"+guid);
             */

            //判断为job执行 还是1001手动执行
            if(hsttype=='1001'){
                time2=datetime;
            }

            //查询当天任务是否已经执行
            def batchguidresult = eliteBean.chaxun_sql("select guid as batchguid from hst_qw_batch_his where 1=1 and hst_type=2 and datetime='"+time2+"'", "dataSource");
            log.debug("batchguidresult=======：" + batchguidresult);

            def batchguid="";
            //重复执行 则跟新当天的批次、否则新增批次任务
            if(batchguidresult.size()>0) {
                batchguid = batchguidresult.get(0).get("batchguid");
                log.debug("batchguid=======：" + batchguid);
                guid=batchguid;
            }
            log.debug("批次guid======="+guid);


            //企微文档 数据ok 判断是否上传成功
            String HSTPATHL1=HSTPATH+time2+"/client_tag_"+time2+".ok";
            //企微文档 数据txt
            String HSTPATHL2=HSTPATH+time2+"/client_tag_"+time2+".txt";
            log.debug("HSTPATH1=======：" + HSTPATHL1);
            log.debug("HSTPATH2=======：" + HSTPATHL2);

            LOACLPATH = LOACLPATH+"/client_tag_"+time2+".txt";
            log.debug("存储下来的路径LOACLPATH============:" + LOACLPATH);

            Util util = new Util();
            def sftpresultok = util.downloadFileSftp(doURL, HSTDEVHST, HSTPWD, Integer.parseInt(HSTPORT), HSTPATHL1, LOACLPATH, 300000);
            log.debug("ok文件是否上传=======：" + sftpresultok);
            if(!sftpresultok){

                //hst_type 企微读取类型 1操作记录回传 2标签回传 3会话存档 4敏感词触发  state 0初始1执行
                //重复执行 则跟新当天的批次、否则新增批次任务
                if(batchguid==""||batchguid==null) {
                    eliteBean.update("insert into hst_qw_batch_his (guid,datetime,createddate,hst_type,state) values ('"+guid+"','"+time2+"',now(),2,0)", "dataSource");
                }else {
                    eliteBean.update("update  hst_qw_batch_his set modifydate=now(),state=0 where guid='"+batchguid+"'", "dataSource");
                }
                def reJoson = "{\"code\":\"0\",\"message\":\"失败，该批次还没有执行完毕\",\"data\":{}}";
                return reJoson;
            }
            //下载sftp文件，从数据库读取配置sftp和路径信息
            def sftpresult = util.downloadFileSftp(doURL, HSTDEVHST, HSTPWD, Integer.parseInt(HSTPORT), HSTPATHL2, LOACLPATH, 300000);
            log.debug("txt文件是否上传:" + sftpresult);
            //下载sftp文件，从数据库读取配置sftp和路径信息
            if (sftpresult) {
                log.debug("文件下载成功");
                File file = new File(LOACLPATH);
                //考虑到编码格式
                InputStreamReader read = new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8");

                //重复执行 则跟新当天的批次、否则新增批次任务
                if(batchguid==""||batchguid==null) {
                    eliteBean.update("insert into hst_qw_batch_his (guid,datetime,createddate,hst_type,state) values ('"+guid+"','"+time2+"',now(),2,1)", "dataSource");
                }else {
                    //数据处理
                    String[] data = new String[2];
                    data[0] ="update  hst_qw_batch_his set modifydate=now(),state=1 where guid='"+batchguid+"'";
                    data[1] ="delete from  hst_client_tag where guid='"+batchguid+"'";
                    def dataresult = eliteBean.updateBatch(data, "dataSource");
                    log.debug("SQL结果:" + dataresult.toString());
                }
                //企微标签临时表 数据处理
                String[] data = new String[2];
                data[0] ="insert into hst_client_tag_his select * from hst_client_tag";
                data[1] ="delete from hst_client_tag"; ;
                def dataresult = eliteBean.updateBatch(data, "dataSource");
                log.debug("SQL结果:" + dataresult.toString());

                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                //逐行读取下载的文件
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    try {
                        log.debug("内容:" + lineTxt);
                        def columnJson = new JsonSlurper().parseText(lineTxt);
                        log.debug("columnJson:" + columnJson);
                        //保存规则ID
                        def custid = columnJson.custid;//华盛号
                        def reportDate = columnJson.reportDate;//统计时间yyyyMMdd
                        def userId = columnJson.userId;//服务顾问企微中的userid
                        def externalUserId = columnJson.externalUserId;//客户userId
                        def groupId = columnJson.groupId;//标签组id
                        def groupName = columnJson.groupName;//标签组名称
                        def tagId = columnJson.tagId;//标签id
                        def tagName = columnJson.tagName;//标签名称
                        def type = columnJson.tagId;//标签类型：1-企业设置, 2-员工自定义
                        def deleted = columnJson.deleted;//是否删除：0否，1是
                        //特殊字符处理
                        groupName=groupName.replace('\'',"");
                        tagName=tagName.replace('\'',"");

                        //写入标签中间表
                        def trow = eliteBean.update("insert into hst_client_tag (custid,reportDate,userId,externalUserId,groupId,groupName,tagId,tagName,type,deleted,createddate,guid) values ('" + custid + "','" + reportDate + "','" + userId + "','" + externalUserId + "','" + groupId + "','" + groupName + "','" + tagId + "','" + tagName + "','" + type + "','" + deleted + "',now(),'"+guid+"')", "dataSource");
                        log.debug("trow:" + trow);

                        //查询当前标签是否存在
                        def labelresult = eliteBean.chaxun_sql("select LABELID as labelid from customerlabeltype where 1=1 and qwtagId='" + tagId + "'", "dataSource");
                        log.debug("labelresult=======：" + labelresult);
                        def labelid;
                        //标签如存在 则获取标签id  更新标签名称
                        if(labelresult.size()>0){
                            labelid = labelresult.get(0).get("labelid");
                            eliteBean.update("update customerlabeltype set LABELCOMMENT='" + tagName + "',qwtype='" + type + "' where qwtagId='" + tagId + "'", "dataSource");
                        }else{//标签不存在则新增
                            //获取标签id
                            labelid = UUID.randomUUID().toString();
                            eliteBean.update("insert into customerlabeltype (LABELID,LABELCOMMENT,LABELBGCOLOR,LABELCOLOR,OWNERTABLE,FOLDERID,WEIGHT,FREQUENCY,qwtagId,qwtype) values ('" + labelid + "','" + tagName + "','#2CC777','#FFFFFF','customerlabelo','','0.00',0,'" + tagId + "','" + type + "')", "dataSource");
                        }
                        log.debug("labelid=======：" + labelid);

                        //查询华盛号客户是否有存在中台系统
                        //def hstcustresult = eliteBean.chaxun_sql("select customer_guid as custguid from customer where customer_id='" + custid + "'", "dataSource");
                        def hstcustresult = eliteBean.chaxun_sql("Select o.objective_guid as objective_guid From Customer c left join objective o  on c.customer_guid=o.customer_guid Where 1=1  and c.Customer_Id = '" + custid + "'  and o. Map_Id='MY48ZX'", "dataSource");
                        log.debug("hstcustresult=======：" + hstcustresult);
                        def objective_guid;
                        //客户存在 则获取customer_guid
                        if(hstcustresult.size()>0) {
                            objective_guid = hstcustresult.get(0).get("objective_guid");
                            log.debug("objective_guid=======：" + objective_guid);
                            //查询标签关系是否存在中台系统
                            def hstcustlabelresult = eliteBean.chaxun_sql("select count(*) as hstcustlabelcount from customerlabelo where RELATION_GUID='" + objective_guid + "' and RELATION_LABELID='" + labelid + "'", "dataSource");
                            def hstcustlabelcount;
                            //如存在，则校验deleted
                            if (hstcustlabelresult.size() > 0) {
                                hstcustlabelcount = hstcustlabelresult.get(0).get("hstcustlabelcount");
                                log.debug("hstcustlabelcount=======：" + hstcustlabelcount);
                                //deleted是否删除：0否，1是
                                if (hstcustlabelcount == 0&&deleted==0) {//不存在则新增客户与标签关系
                                    eliteBean.update("insert into customerlabelo (RELATION_GUID, RELATION_LABELID, CREATEDBY, CREATEDDATE) values ('" + objective_guid + "','" + labelid + "'，'SELITE',now()) ", "dataSource");
                                }else if(hstcustlabelcount >0&&deleted==1){//存在且标识为删除，则删除
                                    eliteBean.update("delete from  customerlabelo where  RELATION_LABELID='"+labelid+"'", "dataSource");
                                }
                            }
                        }

                    } catch (Exception e) {
                        log.error(Util.getERRO(e));
                    }
                }
                //读取完成，关闭并删除临时文件
                read.close();
                file.delete();
                def reJoson = "{\"code\":\"1\",\"message\":\"成功\",\"data\":{}}";
                log.debug("返回Json:" + reJoson);


                log.debug("start HST_API_SftpFile_Client_Tag结束执行任务--------------------------");
                return reJoson;
            }
        } catch (Exception e) {
            log.error("ErrorMessage", e);
            reJson = "{\"Code\":\"-1\",\"Message\":\"错误:" + e.getMessage() + "\",\"data\":null}";
            log.debug("处理异常返回Json:" + reJson);
            return reJson;
        }


    }
    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }
}